<template>
	<LocalityPopup ref="popupRef" :el="el" :top="top" :isFooter="false" :contentHeight="contentHeight"
		:isSafaArea="isSafaArea" @reset="tapResetButton" @confirm="tapConfirmButton">
		<LocalityFiltrate ref="localityFiltrateRef" :only="only" :criteriaList="criteriaList"
			@change="conditionChange" />
	</LocalityPopup>
</template>

<script lang="ts">
	export default {
		// #ifdef MP-WEIXIN
		options: {
			virtualHost: true,
			styleIsolation: 'shared'
		},
		// #endif
	}
</script>
<script setup lang="ts">
	import LocalityPopup from '@/components/locality-popup/locality-popup.vue';
	import LocalityFiltrate from '@/components/locality-filtrate/locality-filtrate.vue';
	import type { Criteria } from '@/types/filtrate-condition';
	import { getQueryParams } from '@/utils/filtrate-condition';
	import { ref, toRaw } from 'vue';
	import { usePopup } from '@/hooks/popup';

	const [popupRef, { openPopup, closePopup }] = usePopup();
	const props = withDefaults(defineProps<{
		el ?: string;
		top ?: string | number;
		contentHeight ?: string;
		isSafaArea ?: boolean;
		criteriaList : Criteria[],
		only ?: boolean;
	}>(), {
		el: '',
		top: 0,
		contentHeight: '80%',
		isSafaArea: false,
		criteriaList: () => [],
		only: false
	});

	const emit = defineEmits<{ confirm : [query: Record<string, any>], change : [query: Record<string, any>] }>();

	const localityFiltrateRef = ref();

	function tapResetButton() {
		localityFiltrateRef.value.reset();
	}

	function getQuery() {
		return getQueryParams(toRaw(props.criteriaList));
	}

	function conditionChange(params : Record<string, any>) {
		if (props.only) {
			emit('change', params);
			return;
		}
		const queryParams = getQuery();
		emit('change', queryParams);
	}

	function tapConfirmButton() {
		const queryParams = getQuery();
		emit('confirm', queryParams);
		popupRef.value.close();
	}

	defineExpose({
		toggle() {
			popupRef.value.toggle();
		},
		open() {
			openPopup();
		},
		close() {
			close();
		},
		reset() {
			tapResetButton();
		}
	})
</script>